<template>
    <div>
        <div class="vs-table-box orderStatus">
            <div class="form_info">
                <el-form ref="form" :model="form" label-width="120px" :rules="rules" inline>
                    <el-form-item label="工号" prop="number">
                        <el-input v-model="form.number" placeholder="请输入工号" clearable style="width:200px"></el-input>
                    </el-form-item>
                    <el-form-item label="岗位" prop="position_id">
                        <el-select v-model="form.position_id" style="width:200px" clearable>
                            <el-option v-for="item in shopList" :key="item.id" :label="item.name"
                                :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model="form.name" placeholder="请输入姓名" clearable style="width:200px"></el-input>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="form.phone" placeholder="请输入手机号" clearable style="width:200px"></el-input>
                    </el-form-item>
                    <el-form-item label="身份证号" prop="id_card">
                        <el-input v-model="form.id_card" placeholder="请输入身份证号" clearable style="width:200px"
                            @blur="blur"></el-input>
                    </el-form-item>
                    <el-form-item label="户籍地址">
                        <el-input v-model="form.address" placeholder="输入姓名和身份证号自动获取" disabled
                            style="width:200px"></el-input>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-input v-model="form.sex" placeholder="输入姓名和身份证号自动获取" disabled
                            style="width:200px"></el-input>
                    </el-form-item>
                    <el-form-item label="生日">
                        <el-input v-model="form.birthday" placeholder="输入姓名和身份证号自动获取" disabled
                            style="width:200px"></el-input>
                    </el-form-item>
                    <el-form-item label="入职时间" prop="into_date">
                        <el-date-picker v-model="form.into_date" type="date" auto-complete="off"
                            @change="getSubsidyByYear" placeholder="选择日期" value-format="yyyy-MM-dd" style="width:200px">
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item label="密码" prop="password" v-if="!form.id">
                        <el-input v-model="form.password" placeholder="请输入密码" autoComplete="new-password" show-password
                            style="width:200px" clearable></el-input>
                    </el-form-item>
                    <el-form-item label="底薪" prop="base_money">
                        <el-input v-model="form.base_money" placeholder="请输入底薪" style="width:200px"
                            clearable></el-input>
                    </el-form-item>
                    <el-form-item label="工龄补贴">
                        <el-input :value="form.subsidy_money" placeholder="请输入工龄补贴" readonly style="width:200px"
                            clearable></el-input>
                    </el-form-item>
                    <el-form-item label="合同时间" prop="contract_end">
                        <div>
                            起始日期：<el-date-picker v-model="form.contract_start" type="date" placeholder="选择日期"
                                value-format="yyyy-MM-dd" style="width:200px">
                            </el-date-picker>
                        </div>
                        <div style="margin-top:20px">
                            结束日期：<el-date-picker v-model="form.contract_end" type="date" placeholder="选择日期"
                                value-format="yyyy-MM-dd" style="width:200px">
                            </el-date-picker>
                            共{{ getDaysBetween }}
                        </div>
                    </el-form-item>
                    <el-form-item style="width:100%" label="头像：" prop="img">
                        <vs-uploading isCompress v-model="form.img" :maxNum="1"></vs-uploading>
                    </el-form-item>
                </el-form>
            </div>
            <div class="vs-bottom-btns btns">
                <el-button @click="utils.backPage()">返回</el-button>
                <el-button @click="subitm" :loading="isBtn" type="primary">确定</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import VsUploading from "../../components/VsUploading";
export default {
    components: {
        VsUploading
    },
    data() {
        const idCardValidity = (rule, code, callback) => {
            var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
            var tip = ""
            var pass = true
            if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
                tip = "身份证号格式错误"
                pass = false;
            } else if (!city[code.substr(0, 2)]) {
                // tip = "地址编码错误"
                tip = "身份证输入错误"
                pass = false
            } else {
                // 18位身份证需要验证最后一位校验位
                if (code.length === 18) {
                    code = code.split('')
                    // ∑(ai×Wi)(mod 11)
                    // 加权因子
                    var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
                    // 校验位
                    var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
                    var sum = 0
                    var ai = 0
                    var wi = 0
                    for (var i = 0; i < 17; i++) {
                        ai = code[i]
                        wi = factor[i]
                        sum += ai * wi
                    }
                    var last = parity[sum % 11];
                    if (parity[sum % 11] != code[17]) {
                        // tip = "校验位错误"
                        tip = "身份证输入错误"
                        pass = false
                    }
                }
            }
            if (!pass) {
                callback(new Error(tip))
            } else {
                callback()
            }
        }
        var img = (rule, value, callback) => {
            // 图片验证
            if (!this.form.img) {
                //hasFmt设置为true/false
                callback(new Error("请上传头像!"));
            } else {
                callback();
            }
        };
        return {
            shopList: [],
            isBtn: false,
            form: {
                number: '',
                position_id: '',
                name: '',
                phone: '',
                id_card: '',
                address: '',
                gender: '',
                birthday: '',
                sex: '',
                into_date: '',
                password: '',
                base_money: '',
                subsidy_money: '',
                contract_start: '',
                contract_end: '',
                img: ''
            },
            rules: {
                number: [{ required: true, message: "请输入工号", trigger: "blur" }],
                position_id: [{ required: true, message: "请选择岗位", trigger: "change" }],
                name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
                phone: [{
                    required: true, validator: (rule, value, callback) => {
                        let phoneReg = this.$Reg.phone;
                        if (!value) {
                            callback(new Error("请输入手机号"));
                        } else if (value && !phoneReg.test(value)) {
                            callback(new Error("请输入正确的手机号"));
                        } else {
                            callback();
                        }
                    }, trigger: "blur"
                }],
                id_card: [{ required: true, message: '请输入身份证号', trigger: 'blur' },
                {
                    pattern: /(^\d{8}(0\d|10|11|12)([0-2]\d|30|31)\d{3}$)|(^\d{6}(18|19|20)\d{2}(0\d|10|11|12)([0-2]\d|30|31)\d{3}(\d|X|x)$)/,
                    message: '请输入正确的身份证号'
                },
                { validator: idCardValidity, trigger: 'blur' }],
                into_date: [{ required: true, message: "请选择入职时间", trigger: "blur" }],
                password: [{ required: true, message: "请输入密码", trigger: "blur" }],
                base_money: [{ required: true, message: "请输入底薪", trigger: "blur" }],
                contract_end: [{ required: true, message: "请选择合同时间", trigger: "blur" }],
                img: [{ required: true, validator: img }],
            },
        }
    },
    computed: {
        getDaysBetween(dateString1, dateString2) {
            dateString1 = this.form.contract_start
            dateString2 = this.form.contract_end
            if (!dateString1 || !dateString2) {
                return 0 + '天';
            }
            var startDate = Date.parse(dateString1);
            var endDate = Date.parse(dateString2);
            if (startDate > endDate) {
                return 0 + '天';
            }
            if (startDate == endDate) {
                return 1 + '天';
            }
            var days = (endDate - startDate) / (1 * 24 * 60 * 60 * 1000);
            return days + 1 + "天";
            // if (days <= 30) {
            //     return days + 1 + "天";
            // } else if (days <= 365) {
            //     return Math.ceil(days / 7) + "周";
            // } else {
            //     return Math.ceil(days / 30) + "月";
            // }
        }
    },
    created() {
        this.getStaffPosition()
        let {
            id,
            type
        } = this.$route.query;
        if (id) {
            this.$route.meta.title = '编辑员工'
            this.getRoom(id);
        }
    },
    methods: {
        async getSubsidyByYear(year) {//查询工龄补贴
            let time = new Date().getTime() - new Date(year).getTime()
            year = parseInt(time / 1000 / 24 / 60 / 60 / 365)
            if (year) {
                let { code, data } = await this.$Http.getSubsidyByYear({ year });
                if (code) {
                    this.form.subsidy_money = data.money;
                }
            } else this.form.subsidy_money = "0.00"
        },
        async getRoom(id) {
            this.loading = true;
            let { code, data } = await this.$Http.getStaff({ id });
            this.loading = false;
            if (code) {
                let { id, number, name, phone, id_card, address, birthday, into_date, password, base_money, subsidy_money, contract_start, contract_end } = data
                let obj = { id, number, name, phone, id_card, address, birthday, into_date, password, base_money, subsidy_money, contract_start, contract_end }
                obj.img = data.img || ''
                obj.position_id = data.position.id
                obj.sex = data.gender == 1 ? '男' : '女'
                obj.gender = obj.sex == '男' ? 1 : 2
                this.form = obj
            }
        },
        async getStaffPosition() {
            this.loading = true;
            let { code, data } = await this.$Http.getStaffPosition({ limit: 100000 });
            this.loading = false;
            if (code) {
                this.shopList = data.data;
            }
        },
        async blur() {
            if (!this.form.name) {
                return this.$message.warning('请输入姓名')
            }
            let obj = { name: this.form.name, id_card: this.form.id_card }
            console.log(JSON.stringify(obj))
            if (this.form.id_card.length == 18) {
                let { code, data } = await this.$Http.getInfoByIdCard({ name: this.form.name, id_card: this.form.id_card })
                if (code) {
                    this.form.address = data.IdCardInfor.area
                    this.form.birthday = data.IdCardInfor.birthday
                    this.form.sex = data.IdCardInfor.sex
                    this.form.gender = this.form.sex == '男' ? 1 : 2
                }
            } else {
                this.form.address = this.form.sex = this.form.birthday = ''
            }
        },
        async subitm() {
            this.$refs['form'].validate(async (valid) => {
                if (!valid) return;
                let obj = Object.assign({}, this.form);
                delete obj.sex
                if (obj.id) {
                    delete obj.password
                }
                this.isBtn = true;
                let { code, data } = await this.$Http.setStaff(obj);
                this.isBtn = false;
                if (code) {
                    this.utils.backPage();
                    this.$message.success(obj.id ? '修改成功!' : '添加成功!');
                }
            });
        },
        dialogBeforeClose() {
            this.dialogVisible = false
        }
    }
}
</script>
<style lang="scss" scoped>
.orderStatus {
    padding: 40px 40px;
    display: flex;
    flex-direction: column;
}
</style>
